/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package nsip.components.ds;

import java.util.logging.Logger;
import se.sics.tasim.props.FactoryStatus;

/**
 * 
 * @author nico.rehwaldt
 */
public class InventoryDataBase {

    private Logger logger = Logger.getLogger("InventoryDataBase");
    
    private Inventory nextDayAvailabilityMap;
    
    private Inventory availabilityMap;
    private TimeAwareInventory demandMap;
    
    /**
     * Creates a new inventory
     */
    public InventoryDataBase() {
        this.availabilityMap = new Inventory();
        this.nextDayAvailabilityMap = new Inventory();
        this.demandMap = new TimeAwareInventory();
    }

    public Inventory today() {
        return availabilityMap;
    }

    public Inventory tomorrow() {
        return nextDayAvailabilityMap;
    }
    
    public TimeAwareInventory demanded() {
        return demandMap;
    }
    
    /**
     * Reserve a number of items in the inventory of tomorrow
     *
     * @param productID
     * @param quantity
     */
    public boolean reserveForNextDay(int productID, int quantity) {
        return nextDayAvailabilityMap.remove(productID, quantity);
    }
    
    public void updateFromStatus(FactoryStatus status) {
        for (int i = 0; i < status.getProductCount(); i++) {
            int productID = status.getProductID(i);
            int count = status.getQuantity(i);

            int projectedCount = availabilityMap.get(productID);
            
            if (projectedCount != count && productID >= 100) {
                logger.severe(
                    "Difference in inventory for #" + productID + ". " +
                    "Expected " + projectedCount + ", got " + count);
            }
            
            availabilityMap.put(productID, count);
            
            // There may have already been changes to the next day inventory
            // Use those changes and 
            int nextDayDiff = nextDayAvailabilityMap.get(productID) - projectedCount;
            nextDayAvailabilityMap.put(productID, count + nextDayDiff);
        }
    }

    public void updateForNextDay(int currentDay) {
        availabilityMap.clear();
        availabilityMap.putAll(nextDayAvailabilityMap);
        demandMap.updateForNextDay(currentDay);
    }

    @Override
    public String toString() {
        return super.toString() + "---------------------\n" +
                    "[today] " + today() + "\n[tomorrow] " + tomorrow() +
                    "\n -------------------------------------------------\n";

    }
}
